<template>
  <div class="json-editor">
    <div class="json-editor-con" ref="jsonEditor"></div>
    <div class="pt-6">
      <a-button block type="primary" @click="putData">更新数据</a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  onMounted,
  ref,
  defineProps,
  onUnmounted,
  defineEmits,
  watch,
} from "vue";

let editor: object;
const jsonEditor = ref<HTMLDivElement | null>(null);
const props = defineProps<{ data: { [key: string]: string } }>();
const emits = defineEmits(["put-data"]);
onMounted(() => {
  if (jsonEditor.value) {
    editor = new window.JSONEditor(jsonEditor.value, { mode: "code" });
  }

  // console.log(props.data);
  setData(props.data);
});
onUnmounted(() => {
  if (editor) {
    editor.destroy();
  }
});
const setData = (data: object) => {
  if (editor) {
    editor.set(data);
  }
};
const getData = (): object => {
  if (editor) {
    return editor.get();
  }
  return {};
};
// 更新更改的数据
const putData = () => {
  emits("put-data", getData());
};
watch(
  () => props.data,
  (nv) => {
    setData(nv);
  }
);
</script>

<style lang="less" scoped>
.json-editor {
  width: 100%;
  height: 100%;
}

.json-editor-con {
  width: 100%;
  height: 100%;
}
</style>
